"""
时间因子 （开盘后多长时间了 离收盘还有多长时间  夜盘23：00也算收盘）
这个时间转换为分钟值
"""
import pandas as pd
import rqdatac as rq
from datetime import timedelta
from ..utility import make_domaint_time_dict


def self_get_factor_df(sec_id):
    symbol_time_dict = make_domaint_time_dict(sec_id)
    result_df = {}
    for symbol, time_dict in symbol_time_dict.items():
        prices = rq.get_price(symbol, start_date="20220801", end_date="20231116", frequency="1m",
                              fields="close", expect_df=False)
        prices.index -= timedelta(minutes=1)
        hour = prices.index.hour
        minute = prices.index.minute

        prices_df = pd.DataFrame({"close": prices})
        prices_df["time"] = hour * 60 + minute
        prices_df = prices_df[time_dict["start"]: time_dict["last"]]

        prices_df["symbol"] = symbol
        result_df[symbol] = prices_df
    df = pd.concat(list(result_df.values()))
    time_since_open = []

    t = 0
    for n, rows in df.iterrows():
        if rows["time"] == 540 or rows["time"] == 1260:
            t = 0
        else:
            t += 1
        time_since_open.append(t)
    df["time_since_open"] = time_since_open

    time_to_close = []
    next_is_close = False
    t = 0
    df.sort_index(ascending=False, inplace=True)
    for n, rows in df.iterrows():
        if next_is_close:
            t = 0
            next_is_close = False
        else:
            t += 1
        if rows["time"] == 540 or rows["time"] == 1260:
            next_is_close = True
        time_to_close.append(t)
    df["time_to_close"] = time_to_close
    df.sort_index(ascending=True, inplace=True)
    return df


def get_factor_df(sec_id, prices):
    print(sec_id, __file__)
    hour = prices["close"].index.hour
    minute = prices["close"].index.minute

    prices_df = pd.DataFrame({"close": prices["close"]})
    prices_df["time"] = hour * 60 + minute

    time_since_open = []

    t = 0
    for n, rows in prices_df.iterrows():
        if rows["time"] == 540 or rows["time"] == 1260:
            t = 0
        else:
            t += 1
        time_since_open.append(t)
    prices_df["time_since_open"] = time_since_open

    time_to_close = []
    next_is_close = False
    t = 0
    prices_df.sort_index(ascending=False, inplace=True)
    for n, rows in prices_df.iterrows():
        if next_is_close:
            t = 0
            next_is_close = False
        else:
            t += 1
        if rows["time"] == 540 or rows["time"] == 1260:
            next_is_close = True
        time_to_close.append(t)
    prices_df["time_to_close"] = time_to_close
    prices_df.sort_index(ascending=True, inplace=True)

    prices["time_since_open"] = prices_df["time_since_open"]
    prices["time_to_close"] = prices_df["time_to_close"]
    return prices
